<template>
  <div>
    <div class="table">
      <Table ref="selection" size="small" :columns="columns" :data="userData" @on-selection-change="onSelectChange"></Table>
    </div>
    <div class="table-bottom">
      <div class="table-btns left-btns">
        <Button type="primary" icon="md-add" @click="addUser">新增</Button>
        <Button :disabled="!(disableId.length>0)" type="primary" icon="md-checkmark" @click="enableHandle()">启用</Button>
        <Button :disabled="!(enableId.length>0)" type="primary" icon="ios-snow" @click="disableHandle()">冻结</Button>
        <Button :disabled="!(selectedId.length>0)" type="primary" icon="ios-trash-outline" @click="deleteHandle(selectedId)">删除</Button>
      </div>
      <div class="table-pages">
        <Page
          :total="pageTotal"
          show-sizer
          show-total
          size="small"
          :page-size-opts="pageSizeOpts"
          @on-change="pageChange"
          @on-page-size-change="pageSizeChange"
        />
      </div>
    </div>
    <Modal
      v-model="modal"
      width="800"
      transfer
      :title="editTitle"
      >
        <template slot="footer">
          <Button type="text" @click="modal=false">取消</Button>
          <Button type="primary" @click="save">保存</Button>
        </template>
        <Form ref="editDom" :model="editData" :label-width="120" :rules="editDataRules">
          <Row>
            <Col span="12">
              <FormItem label="姓名" prop="username">
                <Input :disabled="!!editData.id" v-model="editData.username" placeholder="请输入姓名" :clearable="true"></Input>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="账户" prop="account">
                <Input :disabled="!!editData.id" v-model="editData.account" placeholder="请输入账户" :clearable="true"></Input>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="密码" prop="password">
                <Input v-model="editData.password" placeholder="请输入密码" :clearable="true"></Input>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="有效时间" prop="developDateRange">
                <DatePicker
                  v-model="editData.developDateRange"
                  @on-change="developDateRangeHandle"
                  type="daterange"
                  :start-date="new Date()"
                  placement="bottom-end"
                  placeholder="请输入有效时间"
                  :editable="false"
                >
                </DatePicker>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="状态" prop="enable">
                <Select v-model="editData.enable">
                  <Option value="1">
                    启用
                  </Option>
                  <Option value="0">
                    冻结
                  </Option>
                </Select>
              </FormItem>
            </Col>
          </Row>
        </Form>
    </Modal>
  </div>
</template>
<script>

import { getUserList, addOrEditUser, deleteUser, enableOrDisableUser } from '@/api/server.js';
export default {
  components: {
    
  },
	created(){
		
	},
  mounted() {
    this.getUserListFunc();
  },
  data() {
    return {
      enableId: [],
      disableId: [],
      selectedId: [],
      modal: false,
      editTitle: '新增用户',
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center',
          fixed: 'left'
        },
        {
          key: 'action',
          title: '操作',
          width: 80,
          fixed: 'left',
          render: (h, params) => {
            return h('div',
              [
                h('Button',{
                  props: {
                    type:'primary',
                    size: 'small',
                  },
                  style: {
                    fontSize: '12px',
                    height: '24px !important'
                  },
                  on: {
                    click: () => {
                      this.modal = true;
                      this.editTitle = '编辑用户';
                      let data = JSON.parse(JSON.stringify(params.row));
                      data.developDateRange = [data.startdate, data.enddate];
                      this.editData = data;
                    }
                  },
                },'编辑'),
              ]
            )
          }
        },
        {
          title: '姓名',
          key: 'username'
        },
        {
          title: '账户',
          key: 'account'
        },
        {
          title: '密码',
          key: 'password'
        },
        {
          title: '状态',
          key: 'enable',
          render: (h,params) => {
            return h('span',
            {
              style: {
                border:'1px solid #19be6b',
                borderColor: params.row.enable === '1'? '#19be6b' : '#c5c8ce',
                color: params.row.enable === '1'? '#19be6b' : '#c5c8ce',
                fontSize: '10px',
                padding: '1px 5px',
                borderRadius:"3px",
              }
            },
            params.row.enable === '1'? '启用' : '冻结'
            )
          }
        },
        {
          title: '有效时间',
          key: 'dateRange',
          render: (h,params) => {
            return h('span',
            {},
            params.row.startdate + '~' + params.row.enddate
            )
          }
        }
      ],
      userData: [],
      editDataRules: {
        username: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
        ],
        account: [
          { required: true, message: '账号不能为空', trigger: 'blur' },
          { pattern: /^[a-zA-Z][a-zA-Z0-9]{2,18}$/, message: '账号为字母开头的3至18位数字或字母', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{6,18}$/, message: '密码为6至18位数字或字母', trigger: 'blur' },
        ],
        developDateRange: [
          {
            required: true,
            type: "array",
            message: "请选择开始时间",
            fields: {
              0: {
                required: true,
                type: "date",
                message: "请选择开始时间",
                trigger: "blur,change",
              },
            },
            trigger: "blur,change",
          },
        ],
        enable: [
          { required: true, message: '状态不能为空', trigger: 'change' },
        ],
      },
      editData: {
        username: '',
        accoutn: '',
        password: '',
        startdate: '',
        enddate: '',
        enable: '1',
      },
      pageParam: {
        currentPage:1,
        pageSize:10
      },
      pageTotal:0,
      pageSizeOpts: [10,20,50,100],
    }
  },
	methods:{
    getUserListFunc() {
      getUserList(this.pageParam).then(res => {
        this.pageTotal = res.data.len;
        this.userData = res.data.list;
        this.onSelectChange([])
      })
    },
    onSelectChange(data) {
      let selectedId = [];
      let enableId = [];
      let disableId = [];
      data.forEach(element => {
        selectedId.push(element.id);
        if(element.enable === "1") {
          enableId.push(element.id)
        }else {
          disableId.push(element.id)
        }
      });
      this.selectedId = selectedId;
      this.enableId = enableId;
      this.disableId = disableId;
    },
    addUser() {
      this.modal = true;
      this.editTitle = '新增用户';
    },
    enableHandle() {
      if(this.disableId.length>0) {
        if(this.enableId.length === 0) {
          enableOrDisableUser({type:'1',ids:this.disableId}).then( res => {
            if(res.data) {
              $Message.success('启用成功');
              this.getUserListFunc();
            }else {
              $Message.error('启用失败');
            }
          })
        }else {
          $Message.warning('已启用的用户不能再启用，请重新选择');
        }
      }
    },
    disableHandle() {
      if(this.enableId.length>0) {
        if(this.disableId.length === 0) {
          enableOrDisableUser({type:'0',ids:this.enableId}).then( res => {
            if(res.data) {
              $Message.success('冻结成功');
              this.getUserListFunc();
            }else {
              $Message.error('冻结失败');
            }
          })
        }else {
          $Message.warning('已冻结的用户不能再冻结，请重新选择');
        }
      }
    },
    deleteHandle(ids = []) {
      this.$Modal.confirm({
        title:'删除提示',
        content:`确定删除选中用户吗？`,
        onOk: () => {
          deleteUser({ids:ids}).then( res=> {
            if(res.data) {
              $Message.success('删除成功');
              
              this.getUserListFunc();
            }else {
              $Message.error('删除失败');
            }
          })
        },
        onCancel: () => {

        },

      })
      
    },
    developDateRangeHandle(daterange) {
      this.editData.startdate = daterange[0];
      this.editData.enddate = daterange[1];
    },
    save() {
      this.$refs.editDom.validate(valid => {
        if(valid) {
          addOrEditUser(this.editData).then(res => {
            if(res.data) {
              $Message.success('保存成功');
              this.modal = false;
              this.$refs.editDom.resetFields()
              this.getUserListFunc();
            }else {
              $Message.error('保存失败');
            }
          })
        }
      })
    },
    pageSizeChange(pageSize) {
      this.pageParam.pageSize = pageSize;
      this.getUserListFunc()
    },
    pageChange(page) {
      this.pageParam.currentPage = page;
      this.getUserListFunc()
    },
	},
};
</script>

<style lang="less" scoped>
.table {
  border: 1px solid #eaecf1;
  border-bottom: none;
  margin-bottom: 16px;
  /deep/ .ivu-table-wrapper {
    border-bottom: none;
  }
}
.table-bottom {
  display: flex;
  justify-content: space-between;
  .table-btns {

  }
}
.ivu-date-picker {
  width: 266px;
}
</style>